//
//  FTestViewController.m
//  FFoundation
//
//  Created by 三井 on 2019/11/12.
//

#import "FTestViewController.h"
#import "FTestCell.h"
#import <Masonry/Masonry.h>

@interface FTestViewController ()

@property (nonatomic, strong) UILabel *infoLabel;

@end

@implementation FTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareSubviews];
    
    self.tableView.rowHeight = 50.f;
    [self.tableView registerClass:FTestCell.class forCellReuseIdentifier:NSStringFromClass(FTestCell.class)];
}

- (void)prepareSubviews {
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(0);
    }];
}

- (void)addItem:(void (NS_NOESCAPE ^)(FTestItem * _Nonnull))build {
    FTestItem *item = [FTestItem new];
    build(item);
    [self.items addObject:item];
}

- (void)setInfo:(NSString *)info {
    _info = info;
    
    if (![self.tableView.tableHeaderView isEqual:self.infoLabel]) {
        self.tableView.tableHeaderView = self.infoLabel;
    }
    self.infoLabel.text = info;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FTestCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(FTestCell.class) forIndexPath:indexPath];
    if (!cell) {
        cell = [[FTestCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass(FTestCell.class)];
    }
    
    cell.textLabel.text = self.items[indexPath.row].title;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    FTestItem *item = self.items[indexPath.row];
    
    if (item.action) {
        item.action();
        return;
    }
    
    UIViewController *vc = item.buildViewController ? item.buildViewController() : [[item.klass alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Private
- (NSMutableArray<FTestItem *> *)items {
    if (!_items) {
        _items = [NSMutableArray array];
    }
    return _items;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UILabel *)infoLabel {
    if (!_infoLabel) {
        _infoLabel = [[UILabel alloc] init];
        _infoLabel.numberOfLines = 0;
    }
    return _infoLabel;
}

@end
